package com.uinnova.product.eam.service.impl;

import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.base.exception.ServerException;
import com.uinnova.product.eam.base.util.EamUtil;
import com.uinnova.product.eam.comm.model.ArchDecisionDto;
import com.uinnova.product.eam.comm.model.ArchDecisionListVo;
import com.uinnova.product.eam.comm.model.ArchDecisionTeamResponse;
import com.uinnova.product.eam.comm.model.DecisionParam;
import com.uinnova.product.eam.comm.model.es.ArchDecision;
import com.uinnova.product.eam.feign.workable.FlowableFeign;
import com.uinnova.product.eam.feign.workable.entity.*;
import com.uinnova.product.eam.model.ArchDecisionResponse;
import com.uinnova.product.eam.model.constants.FlowableConstant;
import com.uinnova.product.eam.model.enums.DecisionStatusEnum;
import com.uinnova.product.eam.model.vo.AppSystemQueryVo;
import com.uinnova.product.eam.service.IArchDecisionSvc;
import com.uinnova.product.eam.service.ICISwitchSvc;
import com.uinnova.product.eam.service.asset.AppSystemSvc;
import com.uinnova.product.eam.service.es.ArchDecisionDao;
import com.uinnova.product.vmdb.comm.model.ci.CCcCi;
import com.uinnova.product.vmdb.comm.model.ci.CCcCiClass;
import com.uinnova.product.vmdb.provider.ci.bean.CcCiClassInfo;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.cmdb.base.ESCIInfo;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.permission.base.SysOrg;
import com.uino.bean.permission.base.SysRole;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.business.OrgNodeInfo;
import com.uino.bean.permission.query.CSysUser;
import com.uino.bean.permission.query.SearchKeywordBean;
import com.uino.dao.BaseConst;
import com.uino.dao.cmdb.ESCIClassSvc;
import com.uino.dao.util.ESUtil;
import com.uino.service.permission.microservice.IOrgSvc;
import com.uino.service.permission.microservice.IRoleSvc;
import com.uino.service.permission.microservice.impl.UserSvc;
import com.uino.util.sys.SysUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 架构决策接口实现
 * @author ch
 */
@Service
public class ArchDecisionSvcImpl implements IArchDecisionSvc {

    @Autowired
    private ICISwitchSvc ciSwitchSvc;
    @Resource
    ESCIClassSvc classSvc;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private IOrgSvc iOrgSvc;
    @Resource
    private IUserApiSvc IRoleApiSvc;
    @Autowired
    private ArchDecisionDao decisionDao;
    @Autowired
    private FlowableFeign flowableFeign;
    @Autowired
    private AppSystemSvc appSystemSvc;
    @Autowired
    private UserSvc userSvc;
    @Autowired
    private IRoleSvc roleSvc;
    public static final String ROLE_NAME = "应用系统变更岗";

    public static final String PREFIX = "架构决策-";
    public static final String PUBLISHER = "决策发布人";
    public static final String PRODUCT = "所属产品";
    public static final String SYSTEM_ORG_NAME = "组织名称/用户组织/研发部门";
    private static final String APP_SYSTEM_NAME = "应用系统名称";

    public Long saveOrUpdate(ArchDecisionDto dto){
        ArchDecision copy = EamUtil.copy(dto, ArchDecision.class);
        if(BinaryUtils.isEmpty(copy.getId())){
            copy.setStatus(DecisionStatusEnum.TO_BE_ACCEPTED.val());
        }
        return decisionDao.saveOrUpdate(copy);
    }


    @Override
    public Long submitDecision(ArchDecisionDto dto) {
        SysUser currentUserInfo = SysUtil.getCurrentUserInfo();
        ArchDecision decision = EamUtil.copy(dto, ArchDecision.class);
        //第一次提交-待受理状态
        String taskId = decision.getTaskId();
        TaskRequest taskRequest = new TaskRequest();
        taskRequest.setNextUserIds(dto.getAcceptor());
        if (BinaryUtils.isEmpty(decision.getId()) && BinaryUtils.isEmpty(taskId)) {
            decision.setId(ESUtil.getUUID());
            decision.setStatus(DecisionStatusEnum.TO_BE_ACCEPTED.val());
            ProcessRequest processRequest = new ProcessRequest();
            processRequest.setBusinessKey(decision.getId().toString());
            processRequest.setProcessInstanceName(dto.getTitle());
            processRequest.setOwner(dto.getProposer());
            processRequest.setUserId(dto.getProposer());
            processRequest.setProcessDefinitionKey(FlowableConstant.DECISION_DEFINITION_KEY);
            //开启流程
            PorcessResponse processResponse = flowableFeign.startProcessBindAssignee(processRequest);
            if (BinaryUtils.isEmpty(processResponse)) {
                throw new ServerException("决策流程开启异常,请联系管理员!");
            }
            taskRequest.setAction(FLOWACTION.ACCETP);
            taskId = processResponse.getTaskId();
            decision.setProcessInstanceId(processResponse.getProcessInstanceId());
        } else {
            //不是第一次提交-待决策-重新申请-待发布-已发布
            ArchDecision dec = decisionDao.getById(decision.getId());
            if (dto.getSuccess()) {
                Assert.notNull(decision.getTaskId(), "任务taskId不能为空");
                Assert.notNull(decision.getStatus(), "决策状态status不能为空");
                taskRequest.setAction(FLOWACTION.ACCETP);
                //流程成功开启，更新决策信息状态：待受理通过->待决策
                if (decision.getStatus().equals(DecisionStatusEnum.TO_BE_ACCEPTED.val())) {
                    decision.setStatus(DecisionStatusEnum.WAITING_DECISION.val());
                    decision.setAcceptTime(ESUtil.getNumberDateTime());
                    taskRequest.setNextUserIds(dto.getCompere());
                    //待决策通过->待发布
                } else if (decision.getStatus().equals(DecisionStatusEnum.WAITING_DECISION.val())) {
                    //在这里指定发布人，查询角色信息-决策发布人【目前指定一个，没有或多个都不能进行发布，进行异常提示】
                    List<SysUser> userList = IRoleApiSvc.getUserByRoleName(PUBLISHER);
                    if (BinaryUtils.isEmpty(userList) || userList.size() > 1) {
                        throw new ServerException("请维护架构决策发布人角色信息");
                    }
                    SysUser sysUser = userList.get(0);
                    //角色为 “决策发布人”的id
                    taskRequest.setNextUserIds(sysUser.getLoginCode());
                    //生成一个决策编号
                    decision.setNumber(produceNumber(decision.getResearchStage(), decision.getDecisionStage()));
                    decision.setStatus(DecisionStatusEnum.TO_BE_RELEASED.val());
                    decision.setPublisher(sysUser.getLoginCode());
                } else if (decision.getStatus().equals(DecisionStatusEnum.REAPPLY.val())) {
                    decision.setCreateTime(dec.getCreateTime());
                    decision.setStatus(DecisionStatusEnum.TO_BE_ACCEPTED.val());
                    decision.setAcceptTime(ESUtil.getNumberDateTime());
                    taskRequest.setNextUserIds(dto.getAcceptor());
                } else if (decision.getStatus().equals(DecisionStatusEnum.TO_BE_RELEASED.val())) {
                    taskRequest.setNextUserIds(dto.getCarbonCopyUser());
                    decision.setStatus(DecisionStatusEnum.RELEASED.val());
                }
            } else {
                taskRequest.setAction(FLOWACTION.REJECT);
                //保存驳回原因
                decision.setReason(dto.getReason());
                decision.setCreateTime(dec.getCreateTime());
                //驳回的话，申请时间 应该还是最开始的申请时间；
                decision.setStatus(DecisionStatusEnum.REAPPLY.val());
            }
        }
        taskRequest.setTaskId(taskId);
        if (dto.getReason() != null) {
            taskRequest.setRemarks(dto.getReason());
        } else {
            taskRequest.setRemarks(dto.getRemarks());
        }

        //执行审批
        TaskResponse taskResponse = flowableFeign.completeTask(taskRequest);
        decision.setTaskId(taskResponse.getTaskId());

        return decisionDao.saveOrUpdate(decision);
    }

    /***
     * ADR_YYYY_研发类型阶段编号_决策输出类型编号——三位顺序编号；
     * 编号从001 自增到999，然后是1000
     * eg:  ADR_2022_G_H_001
     * toto : 截取字符前缀， 日期生成器（年），三位数自增序列号
     */
    public String produceNumber(String researchStage, String decisionStage) {
        Assert.notNull(researchStage, "研发阶段类型参数不能为空");
        Assert.notNull(decisionStage, "决策输出类型参数不能为空");
        String loginCode = SysUtil.getCurrentUserInfo().getLoginCode();
        String researchSuffix = researchStage.substring(0, 1);
        String decisionSuffix = decisionStage.substring(0, 1);
        int year = YearMonth.now().getYear();
        //自增序列号
        String returnNum = null;
        String decisionCode = "_eam_decision_code";
        Long redisNum = redisTemplate.opsForValue().increment(decisionCode);
        if (redisNum.toString().length() == 1) {
            returnNum = "00" + redisNum;
        } else if (redisNum.toString().length() == 2) {
            returnNum = "0" + redisNum;
        } else {
            returnNum = redisNum.toString();
        }
        return "ADR_" + year + "_" + researchSuffix + "_" + decisionSuffix + "_" + returnNum;
    }

    @Override
    public List<ArchDecision> getDecisionByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termsQuery("id", ids));
        return decisionDao.getListByQuery(boolQuery);
    }

    @Override
    public ArchDecisionResponse getDecisionById(Long id){
        ArchDecision decision = decisionDao.getById(id);
        if(BinaryUtils.isEmpty(decision)){
            return null;
        }
        ArchDecisionResponse response = EamUtil.copy(decision, ArchDecisionResponse.class);
        List<String> loginCodeList = new ArrayList<>();
        if(!BinaryUtils.isEmpty(decision.getProposer())){
            loginCodeList.add(decision.getProposer());
        }
        if(!BinaryUtils.isEmpty(decision.getAcceptor())){
            loginCodeList.add(decision.getAcceptor());
        }
        if(!BinaryUtils.isEmpty(decision.getCompere())){
            loginCodeList.add(decision.getCompere());
        }
        if(!BinaryUtils.isEmpty(decision.getPlayers())){
            loginCodeList.addAll(decision.getPlayers());
        }
        if(!BinaryUtils.isEmpty(loginCodeList)){
            CSysUser userCdt = new CSysUser();
            userCdt.setLoginCodes(loginCodeList.toArray(new String[]{}));
            List<SysUser> userList = userSvc.getSysUserByCdt(userCdt);
            Map<String, SysUser> userMap = userList.stream().collect(Collectors.toMap(SysUser::getLoginCode, each->each, (k1, k2) -> k2));
            if(!BinaryUtils.isEmpty(decision.getProposer())){
                response.setProposer(userMap.get(decision.getProposer()));
            }
            if(!BinaryUtils.isEmpty(decision.getAcceptor())){
                response.setAcceptor(userMap.get(decision.getAcceptor()));
            }
            if(!BinaryUtils.isEmpty(decision.getCompere())){
                response.setCompere(userMap.get(decision.getCompere()));
            }
            //发布人
            String publisher = decision.getPublisher();
            if(!BinaryUtils.isEmpty(publisher)){
                CSysUser user = new CSysUser();
                user.setLoginCode(publisher);
                List<SysUser> userInfo = userSvc.getSysUserByCdt(user);
                if(!BinaryUtils.isEmpty(userInfo)){
                    response.setPublisher(userInfo.get(0));
                }
            }
            if(!BinaryUtils.isEmpty(decision.getPlayers())){
                List<SysUser> playerResult = new ArrayList<>();
                for (String player : decision.getPlayers()) {
                    SysUser user = userMap.get(player);
                    playerResult.add(user);
                }
                response.setPlayers(playerResult);
            }
        }
        //查询应用系统
        if(!BinaryUtils.isEmpty(decision.getSystemIds())){
            AppSystemQueryVo queryVo = new AppSystemQueryVo();
            queryVo.setPageNum(1);
            queryVo.setPageSize(1000);
            Page<ESCIInfo> appSystemPage = appSystemSvc.queryAppSystemList(queryVo);
            List<ESCIInfo> appList = appSystemPage.getData();
            List<Map<String, String>> appResult = new ArrayList<>();
            if(!BinaryUtils.isEmpty(appList)){
                Map<String, String> codeMap = new HashMap<>();
                for (ESCIInfo each : appList) {
                    if(!BinaryUtils.isEmpty(each.getCiLabel())){
                        String name = each.getCiLabel().replaceAll("[\\[\\]\\\\\"]", "");
                        codeMap.put(each.getCiCode(), name);
                    }
                }
                for (String systemId : decision.getSystemIds()) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", systemId);
                    map.put("name", codeMap.get(systemId));
                    appResult.add(map);
                }
            }
            response.setSystemList(appResult);
        }
        if(!BinaryUtils.isEmpty(decision.getTeamIds())){
            List<ArchDecisionTeamResponse> teamList = getCenterAndTeam();
            Map<Long, String> teamMap = teamList.stream().collect(Collectors.toMap(ArchDecisionTeamResponse::getId, ArchDecisionTeamResponse::getName, (k1, k2) -> k2));
            List<Map<String, String>> teamResult = new ArrayList<>();
            for (String teamId : decision.getTeamIds()) {
                Map<String, String> map = new HashMap<>(16);
                map.put("id", teamId);
                map.put("name", teamMap.get(Long.parseLong(teamId)));
                teamResult.add(map);
            }
            response.setTeamList(teamResult);
        }
        //查询涉及的产品
        if(!BinaryUtils.isEmpty(decision.getProductIds())){
            List<ESCIInfo> infos = getProductsInvolved();
            List<Map<String, String>> productResult = new ArrayList<>();
            if(!BinaryUtils.isEmpty(infos)){
                Map<String, String> productMap = new HashMap<>(16);
                for (ESCIInfo info : infos) {
                    if(!BinaryUtils.isEmpty(info.getCiLabel())){
                        String name = info.getCiLabel().replaceAll("[\\[\\]\\\\\"]", "");
                        productMap.put(info.getCiCode(), name);
                    }
                }
                for (String productId : decision.getProductIds()) {
                    Map<String, String> map = new HashMap<>(16);
                    map.put("id", productId);
                    map.put("name", productMap.get(productId));
                    productResult.add(map);
                }
            }
            response.setProductList(productResult);
        }

        return response;
    }

    @Override
    public Page<ArchDecisionListVo> queryDecisionList(DecisionParam decisionParam) {
        String like = decisionParam.getLike();
        List<Integer> status = decisionParam.getStatus();
        BoolQueryBuilder query = new BoolQueryBuilder();
        if(!BinaryUtils.isEmpty(status)){
            query.must(QueryBuilders.termsQuery("status",status));
        }
        AppSystemQueryVo queryVo = new AppSystemQueryVo();
        queryVo.setPageNum(1);
        queryVo.setPageSize(1000);
        Page<ESCIInfo> appSystemPage = appSystemSvc.queryAppSystemList(queryVo);
        Map<String, String> appNameMap = new HashMap<>();
        List<String> appCodeList = new ArrayList<>();
        if(!BinaryUtils.isEmpty(appSystemPage.getData())){
            for (ESCIInfo each : appSystemPage.getData()) {
                if(BinaryUtils.isEmpty(each.getCiLabel())){
                    continue;
                }
                String name = each.getCiLabel().replaceAll("[\\[\\]\\\\\"]", "");
                appNameMap.put(each.getCiCode(), name);
                if(!BinaryUtils.isEmpty(like) && name.contains(like)){
                    appCodeList.add(each.getCiCode());
                }
            }
        }
        if(!BinaryUtils.isEmpty(like)){
            BoolQueryBuilder likeQueryBuilder = QueryBuilders.boolQuery()
                    .should(QueryBuilders.wildcardQuery("title.keyword", "*" + like.trim() + "*"))
                    .should(QueryBuilders.termsQuery("systemIds.keyword", appCodeList));
            query.must(likeQueryBuilder);
        }
        //按修改时间倒序;
        List<SortBuilder<?>> sorts = new ArrayList<>();
        sorts.add(SortBuilders.fieldSort("modifyTime").order(SortOrder.DESC));
        Page<ArchDecision> pages = decisionDao.getSortListByQuery(decisionParam.getPageNum(), decisionParam.getPageSize(), query, sorts);
        List<ArchDecision> decisionList = pages.getData();
        Page<ArchDecisionListVo> pageVo = new Page<>();
        List<ArchDecisionListVo> listVos = new ArrayList<>();
        if(!BinaryUtils.isEmpty(decisionList)){
            String[] loginCodes = decisionList.stream().map(ArchDecision::getProposer).toArray(String[]::new);
            CSysUser user = new CSysUser();
            user.setLoginCodes(loginCodes);
            List<SysUser> users = userSvc.getSysUserByCdt(user);
            Map<String, String> userMap = new HashMap<>();
            if(!BinaryUtils.isEmpty(users)){
                userMap = users.stream().collect(Collectors.toMap(SysUser::getLoginCode, SysUser::getUserName));
            }
            for (ArchDecision archDecision : decisionList) {
                //申请人loginCode
                String proposer = archDecision.getProposer();
                List<String> systemIds = archDecision.getSystemIds();
                ArchDecisionListVo decisions = EamUtil.copy(archDecision, ArchDecisionListVo.class);
                if(!BinaryUtils.isEmpty(userMap)){
                    String userName = userMap.get(proposer);
                    decisions.setProposer(userName);
                }
                List<String> nameList = new ArrayList<>();
                if(!BinaryUtils.isEmpty(appNameMap)){
                    nameList = systemIds.stream().map(appNameMap::get).filter(Objects::nonNull).collect(Collectors.toList());
                }
                decisions.setLoginCode(proposer);
                decisions.setSystemNameList(nameList);
                listVos.add(decisions);
            }
        }
        pageVo.setData(listVos);
        pageVo.setPageNum(pages.getPageNum());
        pageVo.setPageSize(pages.getPageSize());
        pageVo.setTotalPages(pages.getTotalPages());
        pageVo.setTotalRows(pages.getTotalRows());
        return pageVo;
    }

    @Override
    public List<ESCIInfo> getProductsInvolved() {
        CCcCiClass cCcCiClass = new CCcCiClass();
        cCcCiClass.setClassCodeEqual(PRODUCT);
        List<CcCiClassInfo> resultList = classSvc.queryCiClassInfoList(cCcCiClass, null, false);
        if (CollectionUtils.isEmpty(resultList)) {
            throw new ServerException("【ht_所属产品】分类不存在");
        }
        Long classId = resultList.get(0).getCiClass().getId();
        Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
        //获取产品分类id
        CCcCi cdt = new CCcCi();
        cdt.setClassId(classId);
        return ciSwitchSvc.queryESCIInfoList(domainId, cdt, "", true, LibType.DESIGN);
    }

    @Override
    public List<ArchDecisionTeamResponse> getCenterAndTeam() {
        List<ArchDecisionTeamResponse> result = new ArrayList<>();
        SysOrg org = iOrgSvc.getOrgByOrgFullName(BaseConst.DEFAULT_DOMAIN_ID, SYSTEM_ORG_NAME);
        if(BinaryUtils.isEmpty(org)){
            return result;
        }
        OrgNodeInfo orgTree = iOrgSvc.getOrgTree(BaseConst.DEFAULT_DOMAIN_ID, org.getId(), Boolean.FALSE);
        if(BinaryUtils.isEmpty(orgTree) || BinaryUtils.isEmpty(orgTree.getChildren())){
            return result;
        }
        for (OrgNodeInfo center : orgTree.getChildren()) {
            for (OrgNodeInfo team : center.getChildren()) {
                ArchDecisionTeamResponse teamResponse = new ArchDecisionTeamResponse();
                teamResponse.setId(team.getOrgInfo().getId());
                //中心名称-团队名称
                teamResponse.setName(center.getNodeName()+"-"+team.getNodeName());
                teamResponse.setTeamName(team.getOrgInfo().getOrgName());
                result.add(teamResponse);
            }
        }
        return result;
    }

    @Override
    public void itemDone(String taskId) {
        TaskRequest taskRequest = new TaskRequest();
        taskRequest.setTaskId(taskId);
        taskRequest.setAction(FLOWACTION.ACCETP);
        //执行审批
        flowableFeign.completeTask(taskRequest);
    }

    @Override
    public List<SysUser> getUserByRole() {
        SearchKeywordBean bean = new SearchKeywordBean();
        bean.setPageNum(1);
        bean.setPageSize(100);
        bean.setDomainId(1L);
        bean.setKeyword(ROLE_NAME);
        Page<SysRole> rolePageByQuery = roleSvc.getRolePageByQuery(bean);
        List<SysRole> roleData = rolePageByQuery.getData();
        if(BinaryUtils.isEmpty(roleData)){
            return new ArrayList<>();
        }
        //角色id
        Long roleId = roleData.get(0).getId();
        return userSvc.getUserByRoleId(roleId);
    }

    @Override
    public Page<ArchDecisionListVo> queryDecisionBySystemId(Integer pageNum, Integer pageSize, String systemId) {
        //按修改时间倒序;
        List<SortBuilder<?>> sorts = new ArrayList<>();
        sorts.add(SortBuilders.fieldSort("modifyTime").order(SortOrder.DESC));
        Page<ArchDecision> pages = decisionDao.getSortListByQuery(pageNum, pageSize, QueryBuilders.termQuery("systemIds.keyword", systemId), sorts);
        List<ArchDecision> decisionList = pages.getData();
        Page<ArchDecisionListVo> pageVo = new Page<>();
        List<ArchDecisionListVo> listVos = new ArrayList<>();
        if(!BinaryUtils.isEmpty(decisionList)){
            Map<String, String> appNameMap = this.getAppNameMap(decisionList);
            String[] loginCodes = decisionList.stream().map(ArchDecision::getProposer).toArray(String[]::new);
            CSysUser user = new CSysUser();
            user.setLoginCodes(loginCodes);
            List<SysUser> users = userSvc.getSysUserByCdt(user);
            Map<String, String> userMap = new HashMap<>();
            if(!BinaryUtils.isEmpty(users)){
                userMap = users.stream().collect(Collectors.toMap(SysUser::getLoginCode, SysUser::getUserName));
            }
            for (ArchDecision archDecision : decisionList) {
                //申请人loginCode
                String proposer = archDecision.getProposer();
                List<String> systemIds = archDecision.getSystemIds();
                ArchDecisionListVo decisions = EamUtil.copy(archDecision, ArchDecisionListVo.class);
                if(!BinaryUtils.isEmpty(userMap)){
                    String userName = userMap.get(proposer);
                    decisions.setProposer(userName);
                }
                List<String> nameList = new ArrayList<>();
                if(!BinaryUtils.isEmpty(appNameMap)){
                    nameList = systemIds.stream().map(appNameMap::get).filter(Objects::nonNull).collect(Collectors.toList());
                }
                decisions.setLoginCode(proposer);
                decisions.setSystemNameList(nameList);
                listVos.add(decisions);
            }
        }
        pageVo.setData(listVos);
        pageVo.setPageNum(pages.getPageNum());
        pageVo.setPageSize(pages.getPageSize());
        pageVo.setTotalPages(pages.getTotalPages());
        pageVo.setTotalRows(pages.getTotalRows());
        return pageVo;
    }

    @Override
    public String getApproverByTaskId(String taskId) {
        TaskResponse taskResponse = flowableFeign.getTaskInfoByTaskId(taskId);
        return taskResponse.getUserId();
    }

    /**
     * 获取应用系统名称
     * @param decisionList
     * @return
     */
    private Map<String, String> getAppNameMap(List<ArchDecision> decisionList) {
        Map<String, String> appNameMap = new HashMap<>();
        Set<String> systemIds = new HashSet<>();
        decisionList.stream()
                .filter(decision -> !CollectionUtils.isEmpty(decision.getSystemIds()))
                .forEach(decision -> systemIds.addAll(decision.getSystemIds()));
        if (CollectionUtils.isEmpty(systemIds)) {
            return appNameMap;
        }
        List<ESCIInfo> esciInfos = appSystemSvc.getByIds(new ArrayList<>(systemIds));
        if (!BinaryUtils.isEmpty(esciInfos)) {
            for (ESCIInfo each : esciInfos) {
                Object name = each.getAttrs().get(APP_SYSTEM_NAME);
                if (BinaryUtils.isEmpty(name)) {
                    continue;
                }
                appNameMap.put(each.getCiCode(), name.toString());
            }
        } else {
            List<ESCIInfo> privateEsCiInfo = appSystemSvc.getPrivateByIds(new ArrayList<>(systemIds));
            for (ESCIInfo esciInfo : privateEsCiInfo) {
                Object name = esciInfo.getAttrs().get(APP_SYSTEM_NAME);
                if (BinaryUtils.isEmpty(name)) {
                    continue;
                }
                appNameMap.put(esciInfo.getCiCode(), name.toString());
            }
        }
        return appNameMap;
    }
}
